package com.example.demo.controller;

import com.example.demo.bean.Permission;
import com.example.demo.bean.Role;
import com.example.demo.bean.User;
import com.example.demo.jwt.JwtUtils;
import com.example.demo.service.PermissionService;
import com.example.demo.service.RoleService;
import com.example.demo.service.UserService;
import com.example.demo.util.LocalCache;
import com.example.demo.vo.UserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/Login")
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private JwtUtils jwtUtils;
    @GetMapping("/login")
    public Map login(){
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("code",0);

        UserLogin userLogin=new UserLogin();
        userLogin.setName("guoq");
        userLogin.setPassword("123");
        User user = userService.findUserByUserName(userLogin.getName());
        List<Role> roles = roleService.findById(user.getId());
        user.setRoles(roles);
        for (Role role:roles){
            List<Permission> permissions=permissionService.findByRoleId(role.getId());
            role.setPermissions(permissions);
        }
        if(user==null){
            resultMap.put("msg","failed");
            return resultMap;
        }
        long userId=user.getId();
        String token = jwtUtils.generateToke(userId);
        LocalCache.setMap(token,user);//使用map模拟缓存
        resultMap.put("msg","success");
        resultMap.put("token",token);
        resultMap.put("data",user);
        return resultMap;
    }
}
